import multiprocessing
import sys
import threading

import webview
from PIL import Image
from pystray import Icon, Menu, MenuItem

from config import app_data

Process = multiprocessing.Process
Queue = multiprocessing.Queue


def run_webview(queue):
    threading.Thread(target=web_proc_rev, args=(queue,)).start()
    chinese = {
        'global.quitConfirmation': "确认退出"
    }
    app_data.main_window = webview.create_window('Webview', 'https://baidu.com',
                                                 confirm_close=True, localization=chinese)
    app_data.main_window.events.closing += on_closing

    # 禁止在新的浏览器窗口中打开
    webview.settings["OPEN_EXTERNAL_LINKS_IN_BROWSER"] = False
    # 设置远程调试端口
    webview.settings['REMOTE_DEBUGGING_PORT'] = '59222'
    webview.start(icon='assets/logo.ico')


def web_proc_rev(queue):
    print("web_proc_rev")
    while True:
        # 从队列接收消息
        msg = queue.get()
        print(f"Main Received: {msg}")
        if "open" == msg:
            on_app_open()
        if "exit" == msg:
            on_app_exit()
            print("退出web_proc_rev")
            break


def on_app_open():
    print("on_app_open")
    app_data.main_window.show()


def on_app_exit():
    print("on_app_exit")
    print('正在销毁窗口..')
    app_data.main_window.destroy()
    print('已销毁!')
    sys.exit()


def on_closing(window):
    print('pywebview 窗口正在关闭')
    window.create_confirmation_dialog('提示', '应用已隐藏到托盘，你可以从托盘再次打开')
    window.hide()
    return False


def start_icon_tray():
    open_item = MenuItem('打开', on_app_open)
    exit_item = MenuItem('退出', on_app_exit)
    menu = Menu(open_item, exit_item)
    image = Image.open('assets/logo.ico')
    icon_tray = Icon('Pystray', image, menu=menu)
    icon_tray.run()
